<template>
  <div class="container" @click.stop="clickContainer">
    <input
      ref="input"
      v-model="selectedValue"
      @focus="focus"
      @input="onChange"
    />
    <div class="listContainer">
      <ul :class="[{ active: ifFous }, 'list']">
        <li
          @click.stop="() => select(item)"
          v-for="(item, index) in list"
          :class="[{ selected: (item.value == value) }, 'item']"
          :key="item.value + '-' + index"
        >
          {{ item.label }}
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Selector',
  data() {
    return {
      value: this.initValue,
      selectedValue: this.initValue,
      list: this.options,
      ifFous: false,
    };
  },
  props: {
    initValue: { type: [String, Number] },
    options: { type: Array, default: () => [] },
  },
  model: {
    prop: 'value',
    event: 'onChange',
  },
  created() {
    window.addEventListener("click", this.click);
    if (this.initValue) {
      const result = this.options.find((item) => item.value === this.initValue);
      if (result) {
        this.selectedValue = result.label;
        this.value = result.value;
      }
    }
  },
  beforeDestroy() {
    window.removeEventListener("click", this.click);
  },
  methods: {
    click(e) {
      console.log("click");
      this.ifFous = false;
    },
    clickContainer() {
      this.$refs.input.focus();
    },
    focus() {
      this.ifFous = true;
    },
    blur() {
      this.ifFous = false;
    },
    select(item) {
      console.log('item', item);
      this.$refs.input.focus();
      this.value = item.value;
      this.selectedValue = item.label;
      this.$emit("onChange", item.value);
    },
    onChange(event) {
      const filterRule = event.target.value;
      if (filterRule) {
        this.list = [
          ...this.options.filter((item) => item.label.includes(filterRule)),
        ];
      } else {
        this.list = [...this.options];
      }
    },
  },
};
</script>

<style lang="less" scoped>
.container {
  width: 100%;
  height: 100%;
  position: relative;
  display: inline-block;
  .listContainer {
    position: relative;
    .list {
      top: 8px;
      position: absolute;
      display: none;
      background-color: #fff;
      list-style: none;
      margin: 0;
      padding: 0;
      border: 1px solid #999;
      box-shadow: 0 0 8px #999;
      border-radius: 4px;
      .item {
        line-height: 1.5rem;
        padding: 4px 8px;
        cursor: pointer;
      }
      .item + .item {
        border-top: 1px solid #999;
      }
      .selected {
        color: rgb(36, 170, 248);
      }
    }
    .active {
      display: block;
    }
  }
}
</style>
